<template>
  <div class="pagination">
    <!-- 上 -->
    <button @click="$emit('passPageNo', pageNo - 1)" :disabled="pageNo === 1">上一页</button>
    <button @click="$emit('passPageNo', 1)" v-show="continueNumber.start > 1" :class="{ active: pageNo === 1 }">1</button>
    <button v-show="continueNumber.start > 2">···</button>
    <!-- 中 -->
    <button @click="$emit('passPageNo', c)" v-for="(c, index) in continueNumber.end" :key="index" v-show="c >= continueNumber.start" :class="{ active: pageNo === c }">{{ c }}</button>
    <!-- 下 -->
    <button v-show="continueNumber.end < totalPages - 1">···</button>
    <button @click="$emit('passPageNo', totalPages)" v-show="continueNumber.end < totalPages" :class="{ active: pageNo === totalPages }">{{ totalPages }}</button>
    <button @click="$emit('passPageNo', pageNo + 1)" :disabled="pageNo === totalPages">下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: 'Pagination',
  props: ['total', 'pageSize', 'pageNo', 'continues'],
  computed: {
    // 总共几页
    totalPages() {
      return Math.ceil(this.total / this.pageSize)
    },
    // 连续5个页码的数字
    continueNumber() {
      let start = 0,
        end = 0
      // 连续展示的页数超过了总页数
      if (this.continues > this.totalPages) {
        start = 1
        end = this.totalPages
      } else {
        // 取整求起始页和末尾页
        start = this.pageNo - (this.continues - 1) / 2
        end = this.pageNo + parseInt(this.continues / 2)
        // 如果起始页为负数或者0
        if (start < 1) {
          start = 1
          end = this.continues
        }
        // 如果末尾页超过总页数
        if (end > this.totalPages) {
          end = this.totalPages
          start = this.totalPages - this.continues + 1
        }
      }
      return { start, end }
    },
  },
}
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
.active {
  background: skyblue;
}
</style>
